<template>
  <div class="container">
    <van-popover
      v-model="showPopover"
      trigger="click"
      placement="bottom-end"
      theme="dark"
      :actions="actions"
      @select="onSelect"
    >
      <template #reference>
        <div class="more-option-wrapper flex align-center">
          <van-icon name="add-o" />
        </div>
      </template>
    </van-popover>

    <van-tabs v-model="tabIndex" :ellipsis="false" sticky>
      <van-tab
        :title="
          $store.state.isLogin && tabIndex == 0
            ? ''
            : $store.state.isLogin
            ? groupSelectItem.name == '全部关注'
              ? '关注'
              : groupSelectItem.name
            : '关注'
        "
      >
        <template v-if="$store.state.isLogin && tabIndex == 0" #title>
          <van-dropdown-menu :close-on-click-outside="false">
            <van-dropdown-item
              ref="favorGroup"
              :title="
                groupSelectItem.name == '全部关注'
                  ? '关注'
                  : groupSelectItem.name
              "
            >
              <div class="dropdown-container">
                <div class="flex justify-between">
                  <span class="f-14">默认分组</span>
                  <span class="f-14 color-orange" @click="edit = !edit">{{
                    edit ? "完成" : "编辑"
                  }}</span>
                </div>
                <div class="mt-20 flex flex-wrap">
                  <div
                    v-for="item in myFavorGroup.defaultGroup"
                    :key="item.key"
                    span="6"
                    class="group-item f-12 ellipsis"
                    :class="{
                      'color-orange':
                        groupSelectItem.key == item.key &&
                        groupSelectItem.type == item.type,
                    }"
                    @click="groupChange(item)"
                    v-longpress="longpress"
                  >
                    {{ item.name }}
                  </div>
                </div>
                <div class="f-14 mt-20">我的分组</div>
                <div class="mt-20 flex flex-wrap">
                  <div
                    v-for="item in myFavorGroup.myGroup"
                    :key="item.key"
                    span="6"
                    class="group-item f-12"
                    :class="{
                      'color-orange':
                        groupSelectItem.key == item.key &&
                        groupSelectItem.type == item.type,
                    }"
                    @click="groupChange(item)"
                    v-longpress="longpress"
                  >
                    <div class="ellipsis">
                      {{ item.name }}
                    </div>
                    <van-icon
                      v-if="edit && item.canDel"
                      class="close-icon"
                      name="clear"
                      @click.stop="delGroup(item)"
                    />
                  </div>
                  <div
                    span="6"
                    class="group-add f-12 flex align-center"
                    @click="addGroup"
                  >
                    <van-icon name="plus" class="f-12" />
                    <span class="ml-2 f-12">新建分组</span>
                  </div>
                </div>
              </div>
            </van-dropdown-item>
          </van-dropdown-menu>
        </template>
        <van-pull-refresh
          v-model="favorRefreshIsLoading"
          @refresh="favorOnRefresh"
        >
          <van-list
            class="list"
            :immediate-check="false"
            v-model="favorLoading"
            :finished="favorFinished"
            finished-text="没有更多了"
            @load="favorOnLoad"
          >
            <ul class="favor-list">
              <li
                class="favor-item"
                v-for="item in favorBlogList"
                :key="item.id"
              >
                <div class="header flex align-center">
                  <img class="avatar" :src="item.userInfo.avatar" alt="" />
                  <div class="publish-info">
                    <div class="nickName f-14 color-orange">
                      {{ item.userInfo.nickName }}
                    </div>
                    <div class="create-time f-12">
                      {{ item.createdAt | timeFormat }}
                    </div>
                  </div>
                </div>
                <div class="body">
                  <div class="content f-16">{{ item.content }}</div>
                  <div class="img-list flex">
                    <img
                      class="blog-img"
                      v-for="_item in item.blogImgs"
                      :key="_item.id"
                      :src="_item.url"
                      alt=""
                    />
                  </div>
                </div>
              </li>
            </ul>
          </van-list>
        </van-pull-refresh>
      </van-tab>
      <van-tab title="推荐"> 内容2 </van-tab>
    </van-tabs>
    <!-- 新增分组弹出层-->
    <van-popup :value="addGroupFlag" round :close-on-click-overlay="false">
      <div class="add-group-container">
        <div class="title">新建分组</div>
        <van-form ref="addGroupForm" @submit="onSubmit">
          <div class="input-wrap">
            <van-field
              v-model="groupName"
              class="group-name-input"
              :error="false"
              clearable
              name="groupName"
              label=""
              placeholder="1-16个字符"
              :rules="[
                { required: true, message: '请输入名称' },
                {
                  required: true,
                  validator: groupNameValidator,
                  message: '不能超过16字符',
                },
              ]"
            />
          </div>

          <div class="flex">
            <van-button
              size="small"
              native-type="button"
              class="cancel-btn"
              @click="cancelAddGroup"
            >
              取消
            </van-button>
            <van-button size="small" class="confirm-btn"> 确定 </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
    <!-- 底部栏 -->
    <van-tabbar
      :value="0"
      active-color="#f55555"
      inactive-color="#333"
      placeholder
    >
      <van-tabbar-item icon="home-o">
        <NuxtLink to="/">博mock </NuxtLink>
      </van-tabbar-item>
      <van-tabbar-item icon="video-o"> 视频 </van-tabbar-item>
      <van-tabbar-item icon="search"> 发现 </van-tabbar-item>
      <van-tabbar-item icon="chat-o"> 消息 </van-tabbar-item>
      <van-tabbar-item icon="contact">
        <NuxtLink to="/person"> 我 </NuxtLink>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
export default {
  components: {},
  async fetch() {
    if (this.$store.state.isLogin) {
      const result = await this.$axios.get("/v1/user/getGroup");
      if (result && result.data.code === 200) {
        this.myFavorGroup = result.data.result;
        this.groupSelectItem = result.data.result.defaultGroup[0];
      }
      await this.favorOnLoad();
    } else {
      await this.favorOnLoad();
    }
  },
  data() {
    return {
      // 新增分组弹出层flag
      addGroupFlag: false,
      // 新增分组名称
      groupName: "",
      // 是否编辑分组
      edit: false,
      // tab 索引
      tabIndex: 0,
      // 选中的分组
      groupSelectItem: { name: "全部关注", key: 1, type: 1 },
      // 分组列表
      myFavorGroup: {},
      // 气泡弹出框flag
      showPopover: false,
      // 通过 actions 属性来定义菜单选项
      actions: [{ text: "发mock" }, { text: "选项二" }, { text: "选项三" }],
      //关注分组
      favorBlogList: [],
      //关注分组下拉刷新flag
      favorRefreshIsLoading: false,
      //关注分组下拉刷新完成flag
      favorFinished: false,
      //关注分组当前页
      favorPage: 0,
      //关注分组上拉加载flag
      favorLoading: false,
    };
  },
  methods: {
    //关注分组上拉加载回调
    async favorOnLoad() {
      const params = {
        key: this.groupSelectItem.key,
        page: this.favorPage + 1,
        perPageCount: 10,
      };
      if (this.$store.state.isLogin) {
        const res = await this.$axios.get("/v1/blog/getBlogsWithToken", {
          params,
        });
        if (res && res.data.code == 200) {
          if (this.favorRefreshIsLoading) {
            this.favorBlogList = [];
            this.favorRefreshIsLoading = false;
          }
          this.favorBlogList = [
            ...this.favorBlogList,
            ...res.data.result.blogList,
          ];
          this.favorPage = res.data.result.currentPage;
          this.favorLoading = false;
          if (res.data.result.blogList.length < 10) {
            this.favorFinished = true;
          }
        }
      } else {
        delete params.key;
        const res = await this.$axios.get("/v1/blog/getBlogs", {
          params,
        });
        if (res && res.data.code == 200) {
          if (this.favorRefreshIsLoading) {
            this.favorBlogList = [];
            this.favorRefreshIsLoading = false;
          }
          this.favorBlogList = [
            ...this.favorBlogList,
            ...res.data.result.blogList,
          ];
          this.favorPage = res.data.result.currentPage;
          this.favorLoading = false;
          if (res.data.result.blogList.length < 10) {
            this.favorFinished = true;
          }
        }
      }
    },
    //下拉刷新回调
    favorOnRefresh() {
      setTimeout(() => {
        this.favorFinished = false;
        this.favorPage = 0;
        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        this.favorLoading = true;
        this.favorOnLoad();
      }, 1000);
    },
    //选择气泡弹出框菜单item
    onSelect(action) {
      switch (action.text) {
        case "发mock":
          this.$router.replace("/publish");
          break;
      }
    },
    //长按编辑分组
    longpress() {
      this.edit = true;
    },
    // 新增分组校验规则
    groupNameValidator(value, rule) {
      return value.length <= 16;
    },
    // 取消添加分组
    cancelAddGroup() {
      this.$refs.addGroupForm.resetValidation();
      this.groupName = "";
      this.addGroupFlag = false;
    },
    // 删除分组
    async delGroup(item) {
      try {
        await this.$dialog.confirm({
          message: "确定删除该分组 " + item.name + "吗",
        });
        const res = await this.$axios.delete("/v1/user/delGroup", {
          data: { key: item.key },
        });
        if (res && res.data.code === 200) {
          const index = this.myFavorGroup.myGroup.findIndex(
            (_item) => _item.key === item.key
          );
          if (index != -1) {
            this.myFavorGroup.myGroup.splice(index, 1);
            //如果删除的分组为当前分组，重置分组为默认关注分组
            if (this.groupSelectItem.key === item.key) {
              this.groupSelectItem = this.myFavorGroup.defaultGroup[0];
            }
          }
        }
      } catch (error) {}
    },
    // 选择分组
    groupChange(item) {
      //编辑分组时不能选择分组
      if (this.edit) {
        return;
      }
      this.groupSelectItem = item;
      this.$refs.favorGroup.toggle();
    },
    // 点击添加分组
    addGroup() {
      //编辑分组时不能添加分组
      if (this.edit) {
        return;
      }
      this.addGroupFlag = true;
    },
    // 表单提交
    async onSubmit(values) {
      const res = await this.$axios.post("/v1/user/addGroup", {
        name: values.groupName,
      });
      if (res && res.data.code === 200) {
        this.myFavorGroup.myGroup.push(res.data.result);
        this.groupName = "";
        this.addGroupFlag = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
// 样式穿透
.container ::v-deep .van-tabs--line .van-tabs__wrap {
  margin: 0 70px;
}
.container ::v-deep .van-sticky {
  background: #fff;
}
.container ::v-deep .van-popover__wrapper {
  position: absolute;
  right: 0;
  height: 44px;
  width: auto;
  z-index: 100;
}
.input-wrap ::v-deep .van-cell {
  padding: 0 !important;
}
.container {
  position: relative;
  .more-option-wrapper {
    position: absolute;
    right: 0;
    top: 0;
    height: 44px;
    padding: 0 10px;
    z-index: 101;
  }
  .dropdown-container {
    padding: 10px;
    .group-item {
      position: relative;
      margin: 0 5px 10px;
      width: 22%;
      box-sizing: border-box;
      padding: 3px;
      border: 4px;
      background: #eee;
      text-align: center;
    }
    .close-icon {
      position: absolute;
      right: 0;
      top: 0;
      transform: translate(50%, -50%);
      font-size: 14px;
      color: #999;
    }
    .group-add {
      border: 1px dashed #eee;
      margin: 0 5px 10px;
      width: 22%;
      box-sizing: border-box;
      text-align: center;
    }
    .ml-2 {
      margin-left: 2px;
    }
  }
  .add-group-container {
    padding-top: 20px;
    height: 100%;
    width: 200px;
    background: rgba(255, 240, 245, 0.5);
  }
  .title {
    margin-bottom: 10px;
    font-size: 12px;
    text-align: center;
  }
  .input-wrap {
    padding: 0 10px;
  }
  .group-name-input {
  }
  .cancel-btn {
    width: 50%;
    background: rgba(255, 240, 245, 0.5);
  }

  .confirm-btn {
    width: 50%;
    color: #f55555;
    background: rgba(255, 240, 245, 0.5);
  }
  .list{
    min-height: 550px;
  }
  .favor-list {
    background: #eee;
    .favor-item {
      background: #fff;
      padding: 10px;
      margin-bottom: 10px;
      .header {
        .avatar {
          margin-right: 10px;
          height: 25px;
          width: 25px;
          border-radius: 50%;
        }
        .publish-info {
          .create-time {
            margin-top: 5ox;
            color: #999;
          }
        }
      }
      .body {
        margin-top: 10px;
        .content {
        }
        .img-list {
          flex-wrap: wrap;
          .blog-img {
            max-width: 50%;
            margin: 5px;
          }
        }
      }
    }
  }
}
</style>
